package com.chb.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chb.system.mapper.RoleUserMapper;
import com.chb.system.service.RoleUserService;
import com.chb.system.service.UserService;
import com.hos.entity.sys.RoleUser;
import com.hos.entity.sys.User;
import com.hos.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ：张家琪
 * @date ：Created in 2023/12/21 11:10
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class RoleUserServiceImpl implements RoleUserService {
    @Autowired
    private RoleUserMapper roleUserMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    /**
     * 保存用户的角色信息
     * 分配角色
     *
     * @param userId  用户ID
     * @param roleIds 角色ID
     * @return
     */
    @Override
    public Integer saveRoleUser(Long userId, List<Long> roleIds) {
        int i = roleUserMapper.deleteById(userId);
        for (Long roleId : roleIds) {
            RoleUser roleUser = new RoleUser(userId, roleId);
            this.roleUserMapper.insert(roleUser);
        }
        redisTemplate.delete("menu:leftMenu:" + getUserByToken().getPhone());
        return i;
    }

    private User getUserByToken() {
        String token = WebUtil.getToken();
        String phone = redisTemplate.opsForValue().get("user:" + token);
        return userService.findUserByPhone(phone);
    }
}